<?php

// $Id$

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/sitemap/tcms_sitemap_entry_dbc.class.php');



class TCMS_Sitemap_Generator extends Tangra_Class {
	const SITEMAP_FILE = 'sitemap.xml';

	public static function generate(DB_Connection $dbc, $tple, $scratch_dir, $prefix) {
		$c = 0;
		$tmp1 = array();

		$sql = TCMS_Sitemap_Entry_DBC::sql_get_entries_for_sitemap($dbc);
		$rez = $dbc->execute($sql);
		while($rez_obj = $rez->fetch_object()) {
			if ($rez_obj->PATH != '/') {
				$tmp1[$c]['path'] = str_replace('%2F', '/', urlencode($rez_obj->PATH));
			} else {
				$tmp1[$c]['path'] = '';
			}

			$tmp1[$c]['weight'] = $rez_obj->WEIGHT / 10;
			$tmp1[$c]['change_freq'] = TCMS_Sitemap_Generator::resolve_change_freq($rez_obj->CHANGE_FREQ);
			$c++;
		}


		$tmp2 = array();
		$c = 0;

		$sql = TCMS_VPage_DBC::sql_get_pages_for_sitemap();
		$rez = $dbc->execute($sql);
		while($rez_obj = $rez->fetch_object()) {
			$tmp2[$c]['path'] = str_replace('%2F', '/', urlencode($rez_obj->PATH));
			$tmp2[$c]['weight'] = $rez_obj->SITEMAP_WEIGHT / 10;
			$tmp2[$c]['change_freq'] = TCMS_Sitemap_Generator::resolve_change_freq($rez_obj->SITEMAP_CHANGE_FREQ);
			$timestamp = datetime_to_timestamp($rez_obj->LAST_MODIFIED);
			$w3c_date = gmdate('Y-m-d\TH:i:s', $timestamp).'Z';
			$tmp2[$c]['last_modified'] = $w3c_date;
			$c++;
		}

		$pages = array_merge($tmp1, $tmp2);


		$tple->assign('pages', $pages);
		$tple->assign('prefix', $prefix);

		$sitemap_content = $tple->fetch('modules/tangra_cms/sitemap.tpl');

		$filepath = $scratch_dir.TCMS_Sitemap_Generator::SITEMAP_FILE;
		file_put_contents($filepath, $sitemap_content);
	}



	private static function resolve_change_freq($freq) {
		switch($freq) {
			case 0:
				$ret = 'always';
				break;
			case 1:
				$ret = 'hourly';
				break;
			case 2:
				$ret = 'daily';
				break;
			case 3:
				$ret = 'weekly';
				break;
			case 4:
				$ret = 'monthly';
				break;
			case 5:
				$ret = 'yearly';
				break;
			case 6:
				$ret = 'never';
				break;
			default:
				$ret = 'monthly';
				break;
		}

		return $ret;
	}
}